#include "mainwidget.h"
#include "ui_mainwidget.h"

#include"goodsinput.h"
#include"goodsoutput.h"
#include"addproduct.h"
#include"goodsum.h"
#include<QDebug>


MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    setFixedSize(this->width(),this->height());
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);

    //设置背景颜色
    QPalette plt;
    plt.setColor(QPalette::Window,QColor(180,220,150));
    this->setPalette(plt);

    connectMySQLDBFunc();    //连接数据库
    InitTableWidgetFunc();   //初始化表格



}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::connectMySQLDBFunc()  //连接数据库
{
    QSqlDatabase db=QSqlDatabase::addDatabase("QODBC");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setDatabaseName("stockmsdb");//odbc数据源配置的名称
    db.setPassword("123456");//安装mysql的密码

    if(!db.open())
    {
        QMessageBox::information(this,"提示","MySQL数据库连接失败");
        return;
    }


}



void MainWidget::on_pushButton_Add_clicked()  //新增商品
{
    AddProduct *addproduct=new AddProduct();
    connect(addproduct,&AddProduct::addSuccesseded,this,&MainWidget::InitTableWidgetFunc);
    addproduct->show();
}

void MainWidget::on_pushButton_delete_clicked()  //删除商品
{

    //获取当前行
    int iRow=ui->tableWidget->currentRow();
    if(iRow==-1)
    {
        QMessageBox::information(this,"tip","请选择要删除的商品");
        return;
    }

    int id=ui->tableWidget->model()->index(iRow,0).data().toInt();  //获取当前行id

    int iClick=QMessageBox::warning(this,"警告","是否要执行删除操作，此操作不可逆",
                                    QMessageBox::Yes,QMessageBox::No);
    if(iClick==QMessageBox::Yes)
    {
        QSqlQuery query;
        QString str="delete from stockdatatable where stockId=?";
        query.prepare(str);
        query.addBindValue(id);

        if (query.exec())
        {
            InitTableWidgetFunc();
        } else
        {
            QMessageBox::critical(this, "错误", "商品删除失败: " + query.lastError().text());
        }

     }


}

void MainWidget::on_pushButton_enter_clicked()   //商品入库
{
    GoodsInput *goodinput=new GoodsInput();
    connect(goodinput,&GoodsInput::warehouseSucceeded,this,&MainWidget::InitTableWidgetFunc);
    goodinput->show();
}

void MainWidget::on_pushButton_out_clicked()  //商品出库
{
    GoodOutput *goodoutput=new GoodOutput();
    connect(goodoutput,&GoodOutput::deliverSucceeded,this,&MainWidget::InitTableWidgetFunc);
    goodoutput->show();
}


void MainWidget::on_pushButton_load_clicked()    //导出表格，生成excel文件保存
{
    // 创建 Excel 应用程序对象
    QAxObject* excel = new QAxObject("Excel.Application");

    if (!excel)
    {
        QMessageBox::critical(this, "错误", "无法启动 Excel 应用程序");
        return;
    }

    // 设置 Excel 应用程序可见
    excel->setProperty("Visible", false);
    excel->setProperty("DisplayAlerts",false);  //禁止 Excel 在操作过程中显示警告对话框。
    // 获取工作簿集合对象
    QAxObject* workbooks = excel->querySubObject("Workbooks");

    // 在工作簿集合中添加一个新的工作簿
    QAxObject* workbook = workbooks->querySubObject("Add");

    // 获取新工作簿中的第一个工作表
    QAxObject* worksheet = workbook->querySubObject("Worksheets(int)", 1);

    QAxObject* cell ;

    //写入表头数据
    for (int i = 1; i<= ui->tableWidget->columnCount(); i++)
    {
        QTableWidgetItem* headerItem = ui->tableWidget->horizontalHeaderItem(i - 1);

        if (!headerItem)
        {
            QMessageBox::information(this,"ooo","表格表头获取失败");
            break;
        }
        cell=worksheet->querySubObject("Cells(int,int)",1,i);

        cell->setProperty("RowHeight",28);

        if (!cell)
        {
            QMessageBox::critical(this, "错误", "获取 Excel 表头单元格对象失败，停止导出");
            break;
         }

         cell->dynamicCall("SetValue(const QString&)", headerItem->data(0).toString());


    }

    // 遍历 QTableWidget 的每一行和每一列（从第二行开始写入数据）
    for (int j = 2; j <= ui->tableWidget->rowCount() ; j++)
    {
       for(int k=1;k<=ui->tableWidget->columnCount();k++)
       {
           QTableWidgetItem* tableItem = ui->tableWidget->item(j - 2, k - 1);
           if (!tableItem)
           {
              // 若项不存在，可选择跳过当前单元格,这样就不会有空指针引发报错
               continue;

           }
           cell=worksheet->querySubObject("Cells(int,int)",j,k);
           cell->dynamicCall("SetValue(const QString&)",tableItem->text()+"\t");
       }

    }

    QString filePath = QFileDialog::getSaveFileName(this, tr("保存 Excel 文件"), "新建XLSX工作表.xlsx", tr("Excel Files (*.xlsx)"));

    if (filePath.isEmpty())
    {
        QMessageBox::information(this, "提示", "未选择保存路径，文件未保存");
        workbook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");
        delete excel;
        return;
    }

    // 保存工作簿
    workbook->dynamicCall("SaveAs(const QString&)", filePath);

    // 关闭工作簿和 Excel 应用程序
    workbook->dynamicCall("Close()");
    excel->dynamicCall("Quit()");

    // 释放 Excel 应用程序对象
    delete excel;

}

void MainWidget::on_pushButton_sum_clicked()    //数据汇总
{
    GoodSum *goodsum=new GoodSum();
    goodsum->show();
}

void MainWidget::on_pushButton_query_clicked()     //查询商品信息
{
    if(ui->lineEdit_id->text().isEmpty())
    {
        QMessageBox::information(this,"tip","请输入id");
        return;
    }
    QSqlQuery query;
    QString strid="stockId=";
    strid=strid+ui->lineEdit_id->text();

    QString str=QString("select *from stockdatatable where %1").arg(strid);
    //执行查询语句
    if (!query.exec(str))
    {
        QMessageBox::critical(this, "错误", QString("查询失败: %1").arg(query.lastError().text()));
        return;
    }

    //没有查询到结果，即id不存在
    if(!query.next())
    {
        QMessageBox::information(this,"tip","没有此id对应的商品,请重新输入");
        ui->lineEdit_id->clear();
        ui->lineEdit_id->setFocus();
        return;
    }

    //先清空表格
    ui->tableWidget->clearContents();
    ui->lineEdit_id->clear();

    //因为前面已经调用过一次 query.next()，所以需要将游标移回第一条记录
    query.seek(-1);
    //显示查询数据
    while(query.next())
    {
            //将数据库里面的数据读取出来转化成相应的字符串
        QString strId=query.value(0).toString();
        QString strName=query.value(1).toString();
        QString strAmout=query.value(2).toString();
        QString strUnitPrice=query.value(3).toString();
        QString strSupplier=query.value(4).toString();
        QString strDirect=query.value(5).toString();
        QString strWareHouse=query.value(6).toString();
        QString strDeliver=query.value(7).toString();
        QString strMarks=query.value(8).toString();

        ui->tableWidget->setItem(0,0,new QTableWidgetItem(strId));
        ui->tableWidget->setItem(0,1,new QTableWidgetItem(strName));
        ui->tableWidget->setItem(0,2,new QTableWidgetItem(strAmout));
        ui->tableWidget->setItem(0,3,new QTableWidgetItem(strUnitPrice));
        ui->tableWidget->setItem(0,4,new QTableWidgetItem(strSupplier));
        ui->tableWidget->setItem(0,5,new QTableWidgetItem(strDirect));
        ui->tableWidget->setItem(0,6,new QTableWidgetItem(strWareHouse));
        ui->tableWidget->setItem(0,7,new QTableWidgetItem(strDeliver));
        ui->tableWidget->setItem(0,8,new QTableWidgetItem(strMarks));
        ui->tableWidget->update();
    }


}

void MainWidget::InitTableWidgetFunc()   //表格初始化
{

    ui->tableWidget->setColumnCount(9);
    ui->tableWidget->setRowCount(200);
    //设置表格控件字体大小
    ui->tableWidget->setFont(QFont("宋体",9));

    //设置表格控件标题(表头)
    ui->tableWidget->setHorizontalHeaderLabels(QStringList()
              <<"编号"<<"名称"<<"数量"<<"单价"<<"供应商家"<<"负责人"<<"入库时间"<<"出库时间"<<"备注");

    ui->tableWidget->setColumnWidth(0,60);
    ui->tableWidget->setColumnWidth(1,90);
    ui->tableWidget->setColumnWidth(2,60);
    ui->tableWidget->setColumnWidth(3,60);
    ui->tableWidget->setColumnWidth(4,120);
    ui->tableWidget->setColumnWidth(5,70);
    ui->tableWidget->setColumnWidth(6,120);
    ui->tableWidget->setColumnWidth(7,120);
    ui->tableWidget->setColumnWidth(8,40);

    //先清空表格，再读取数据库
    ui->tableWidget->clearContents();

    QSqlQuery query;
    QString str=QString("select *from stockdatatable");
    query.exec(str);
    //将数据库里面的数据读取出来转化成相应的字符串
    int i=0;
    while(query.next())
    {
        QString strId=query.value(0).toString();
        QString strName=query.value(1).toString();
        QString strAmout=query.value(2).toString();
        QString strUnitPrice=query.value(3).toString();
        QString strSupplier=query.value(4).toString();
        QString strDirect=query.value(5).toString();
        QString strWareHouse=query.value(6).toString();
        QString strDeliver=query.value(7).toString();
        QString strMarks=query.value(8).toString();

        //
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(strId));
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(strName));
        ui->tableWidget->setItem(i,2,new QTableWidgetItem(strAmout));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(strUnitPrice));
        ui->tableWidget->setItem(i,4,new QTableWidgetItem(strSupplier));
        ui->tableWidget->setItem(i,5,new QTableWidgetItem(strDirect));
        ui->tableWidget->setItem(i,6,new QTableWidgetItem(strWareHouse));
        ui->tableWidget->setItem(i,7,new QTableWidgetItem(strDeliver));
        ui->tableWidget->setItem(i,8,new QTableWidgetItem(strMarks));
        i++;

    }
}







//
